/**
 * @name: findSiblingIds
 * @description: 获取传入id的兄弟节点
 * @param {Array} list //树形机构数据
 * @param {String} id //需要查找的id
 * @return {Array} //返回兄弟节点
 */
function findSiblingIds(list, id) {
  let node;
  for (let i in list) {
    if (list[i].id === id) {
      return list.filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = findSiblingIds(list[i].children, id);
      if (node) return node.filter((v) => v.id !== id);
    }
  }
  return node;
}

function addStationName(list) {
  list.forEach((item) => {
    if (item.level == 1) {
      item.label = item.orgName;
      item.id = item.orgId;
    }
    if (item.level == 2) {
      item.label = item.stationName;
      item.id = item.stationId;
    }
    if (item.level == 3) {
      item.label = item.unitsName;
      item.id = item.unitsId;
    }

    if (item.children) {
      addStationName(item.children);
    }
  });
  return list;
}

// 传入一个id获取它父级的id
function getAllParentNodes(list, id) {
  if (list.length === 0 || !list) return [];
  let node;

  for (let i in list) {
    if (list[i].id === id) {
      return [list[i]].filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = getAllParentNodes(list[i].children, id);
      if (node) return node.concat(list[i]).filter((v) => v.id !== id);
    }
  }
  return node;
}

function msgFn(deviceid, imgSource, width, height) {
  return JSON.stringify({
    func: "showImageOnDevices",
    param0: deviceid,
    param1: imgSource,
    param2: width,
    param3: height,
  });
}

let deviceList = [
  {
    id: "3800756696423979041",
    name: "新西线16903开关",
    gh: "100kW",
    rl: "4000kWh",
  },
  {
    id: "3800756696423979049",
    name: "新西线16903开关",
    gh: "1000kW",
    rl: "2000kWh",
  },
  {
    id: "3800756696423979182",
    name: "新西线16903开关",
    gh: "500kW",
    rl: "1000kWh",
  },
];

import { Message } from "element-ui";
import {
  queryStationFileList,
  updateStationInfoFile,
  queryStationTestNumber,
} from "@/api/windPower.js";
import {
  adjustRegulationList,
  regulationOrgList,
  stationTypeList,
  voltageLevelList,
  queryUnitsNameList,
  queryStationNameList,
  queryOfExperimentalresults,
  updateStationFileWarn,
} from "@/api/dict.js";
import TestResultEdit from "@/views/testResult/testResultEdit/testResultEdit.vue";
import { queryTreeData } from "@/api/common.js";
import { selectEnergyStoragePlanScheme } from "@/api/second.js";
import { queryPlansData } from "@/api/common.js";
import { queryDetailTableList } from "@/api/configurationCheck.js";

export default {
  components: { TestResultEdit },
  name: "maintenanceRecord",
  data() {
    return {
      queryStationFileList,
      queryStationNameList,
      queryUnitsNameList,
      queryDetailTableList,
      formData: new FormData(),
      excelData: [],
      columns: [],
      getFrom: {}, //每行的数据
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      adjustRegulationLists: [], //上下调投入分类下拉框的数据
      voltageLevelLists: [], //电压等级下拉框的数据
      addDialogVisibleTitle: "新增",
      id: 0,
      dataTree: [],
      currentLivingId: "",
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],

      defaultProps: {
        children: "list",
        label: "name",
      },
      // 当前馈线id
      currentFeederId: "",
      queryDetailParam: {
        planId: "",
        page: {
          pageIndex: 1,
          pageSize: 10,
        },
      },
      operate: "add",
      testNumberList: [], //测试序号
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      secondHeards: [
        {
          name: "规划前",
          value: "type1",
        },
        {
          name: "规划后",
          value: "type2",
        },
      ],
      headList: [
        {
          name: "规划节点",
          value: "nodeId",
          noSort: true,
          width: "108",
        },
        {
          name: "储能规划功率(kW)",
          value: "ratedP",
          noSort: true,
          width: "135",
        },
        {
          name: "储能规划容量(kWh)",
          value: "capacity",
          noSort: true,
          width: "140",
        },
      ],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "80px",
      // 预览弹框f
      dialogPreVisible: false,
      paramData: [],
      checkList: [],
      checkId: "",
      queryParamStationId: "",
      showXLSX: false,
      xData: [
        "4.1",
        "4.2",
        "4.3",
        "4.4",
        "4.5",
        "4.6",
        "4.7",
        "4.8",
        "4.9",
        "4.10",
        "4.11",
        "4.12",
      ],
      dxtUrl: "",

      // 变电站下拉列表
      stationOptions: [
        {
          value: "001",
          label: "变电站1",
        },
        {
          value: "002",
          label: "变电站2",
        },
      ],
      // 馈线下拉列表
      lineOptions: [
        {
          value: "001",
          label: "变电站1",
        },
        {
          value: "002",
          label: "变电站2",
        },
      ],
      upForm: {
        // 缓存状态类型
        statusType: "",
      },

      // 缓存状态类型列表
      statusTypeOptions: [
        {
          value: "001",
          label: "倒送状态",
        },
        {
          value: "002",
          label: "高负载状态",
        },
        {
          value: "003",
          label: "冬季典型状态",
        },
        {
          value: "004",
          label: "夏季典型状态",
        },
        {
          value: "005",
          label: "春秋典型状态",
        },
      ],
      bottomForm: {
        // 变电站id
        date: this.dateFormat(new Date().getTime()),
      },
      value: 1,
      options: [
        {
          value: 1,
          label: "倒送状态",
        },
        {
          value: 2,
          label: "高负载状态",
        },
        {
          value: 3,
          label: "冬季典型状态",
        },
        {
          value: 4,
          label: "夏季典型状态",
        },
        {
          value: 5,
          label: "春秋典型状态",
        },
      ],
      filterText: "",
      queryData: {
        planId: "1",
        feederStatusType: 1,
      },
      planObj: {
        planName: "",
        energyPlanTarget: "",
        energyConstraint: "",
        feederId: "",
        countConstraint: "",
        pconstraint: "",
      },
      // 树节点相关
      allIds: [],
      defaultExpandedNode: [],
      currentKey: "",

      isBubble: false,
    };
  },

  mounted() {
    this.getTreeFn();
    this.initIframeFn();
    this.dxtInit();

    window.addEventListener("message", function (e) {
      let data = JSON.parse(e.data);
      if (data.fun == "graphLoadFinish") {
        document
          .getElementById("iframe")
          .contentWindow.postMessage(
            msgFn(
              [
                "3800756610524633262",
                "3800756610524633121",
                "3800756610524633129",
              ],
              "energyStorageBlack.png",
              40,
              40
            ),
            "*"
          );
      }
      if (data.fun == "clickDeviceImage") {
        this.isBubble = !this.isBubble;
        let param = "";
        if (this.isBubble) {
          let showObj = deviceList.filter((item) => item.id == data.param0);
          param = `;isReload=1;graph=%E6%96%B0%E8%A5%BF169%E7%BA%BF%E5%8D%95%E7%BA%BF%E5%9B%BE.sln.pic.g;facBubble=${data.param0}_align=0^fs=16^alignSec1=0^alignSec2=0^ts=节点名称：${showObj[0].name}@n储能规划：${showObj[0].gh}@n储能容量：${showObj[0].rl}`;
        } else {
          param = `;isReload=1;graph=%E6%96%B0%E8%A5%BF169%E7%BA%BF%E5%8D%95%E7%BA%BF%E5%9B%BE.sln.pic.g;`;
        }
        let msg = JSON.stringify({ func: "urlUtilGraph", param0: param });
        setTimeout(() => {
          document.getElementById("iframe").contentWindow.postMessage(msg, "*");
        }, 1000);
      }
    });
  },
  created() {
    // this.regulationOrgList()
    // this.stationTypeList()
    // this.adjustRegulationList()
    // this.voltageLevelList()
    // this.getTreeData()
    // this.queryStationTestNumber()
    // this.getTreeFn();
  },
  watch: {
    filterText(val) {
      this.$refs.equipmentTree.filter(val);
    },
  },
  methods: {
    handleCheck(data, e) {
      if (data.id) {
        this.queryData.planId = data.id;
        this.getPlanListFn();
        // this.querygre();
        // this.$refs.windPowerTable.getDataInit();
        // this.$refs.windPowerTable2.getDataInit();
      }
    },

    querygre() {
      console.log(this.queryData);
      selectEnergyStoragePlanScheme(this.queryData).then((res) => {
        if (res.resultCode === 0) {
          // this.dataTree = res.data
          console.log(res.data);
          this.planName = res.data.planName;
          this.energyPlanTarget = res.data.energyPlanTarget;
          this.pconstraint = res.data.pconstraint;
          this.energyConstraint = res.data.energyConstraint;
          this.feederId = res.data.feederId;
          this.countConstraint = res.data.countConstraint;
        }
      });
    },

    dateFormat(val) {
      let date = new Date(val);
      let year = date.getFullYear();
      let month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : "0" + (date.getMonth() + 1);
      let day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();

      return year + "-" + month + "-" + day;
    },
    // dxtInit(){
    // 	let gzqytmp='keyidrect=FFCC33_';
    // 	if(this.gzqyid)gzqytmp+=this.gzqyid;
    // 	let faultdescId = this.deviceIdlist.join(':');
    // 	gzqytmp += ';faultdesc=' + faultdescId;
    // 	let bigStr = 'graph=' + this.rowParamsObj.dxt + ';isClient=1;menubarshow=0;appmode=3;isFault=1;100p;100p;isgray=0;' + gzqytmp;
    // 	console.log(bigStr);
    // 	let msg = JSON.stringify({
    // 		fun: 'urlUtilGraph',
    // 		param0: bigStr,
    // 	});
    // 	setTimeout(() => {
    // 		this.$refs.dxt.contentWindow.postMessage(msg, '*');
    // 	}, 2000)
    // },
    dxtInit() {
      // this.dxtUrl=dxtUrl+'?menubarshow=0;toolbarshow=0;graph=' + this.rowParamsObj.dxt;

      this.dxtUrl =
        "http://pdyzz.test.com.cn/graph/Navigator.html?graph=新西169线单线图.sln.pic.g";
    },

    // 获取渲染树的数据
    getTreeData(data) {},
    // 下拉框change事件
    inputChange(val) {
      // console.log(val, "搜索下拉框val");
      // console.log(this.$refs.equipmentTree.queryInputListCopy, "搜索下拉框val");
      let param = {
        stationId: val,
      };
      this.getTreeData(param);
    },

    // 获取表格多行选中的数据  点击行选中
    getMultipleSelection2(row) {
      this.tableData = JSON.parse(JSON.stringify(row));
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    getMultipleSelection() {
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.windPowerTable.multipleSelection)
      );
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    // 检索
    searchList() {
      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
      });
    },

    handleClear() {
      this.getTreeData();
    },

    // 给树节点添加唯一标识
    dataTreeFn(data) {
      for (const item of data) {
        if (item.list) {
          item.id = item.name;
          this.dataTreeFn(item.list);
        } else {
          item.id = item.id;
          this.allIds.push(item.id);
        }
      }
    },

    // 获取树结构
    async getTreeFn() {
      let { resultCode, data } = await queryPlansData(this.queryDetailParam);
      if (resultCode == 0) {
        this.$nextTick(() => {
          this.dataTree = data;
          this.dataTreeFn(data);
          this.currentKey = this.allIds[0];

          if (this.currentKey) {
            // 默认展开第一条
            this.defaultExpandedNode.push(this.currentKey);
            this.queryDetailParam.planId = this.currentKey;
            this.expandDefault();
            this.handleNodeClick({ id: this.currentKey });
          }
        });
      }
    },

    // 默认展开第一条
    expandDefault() {
      if (this.currentKey) {
        this.$nextTick(() => {
          this.$refs.equipmentTree.setCurrentKey(this.currentKey);
        });
      }
    },
    // 树搜索
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 单击节点
    handleNodeClick(data) {
      if (!data.hasOwnProperty("list") || typeof data == "number") {
        let id = typeof data == "number" ? id : data.id;
        this.queryDetailParam.planId = id;
        this.queryData.planId = id;
        this.searchList();
        this.getPlanListFn();
      }
    },

    // 储能规划方案
    async getPlanListFn() {
      let { resultCode, data } = await selectEnergyStoragePlanScheme(
        this.queryData
      );
      if (resultCode === 0 && data) {
        this.planObj.planName = data.planName;
        this.planObj.energyPlanTarget = data.energyPlanTarget;
        this.planObj.pconstraint = data.pconstraint;
        this.planObj.energyConstraint = data.energyConstraint;
        this.planObj.feederId = data.feederId;
        this.planObj.countConstraint = data.countConstraint;
      }
    },

    // 网架图
    initIframeFn() {
      // 网架图地址
      this.dxtUrl =
        "http://pdyzz.test.com.cn/graph/Navigator.html?graph=新西169线单线图.sln.pic.g";

      // 点位
      let msg = JSON.stringify({
        func: "showImageOnDevices",
        param0: ["PD_10100000_1021041144"],
        param1: "energyStorageBlack.png",
        param2: 50,
        param3: 50,
      });

      this.$nextTick(() => {
        document.getElementById("iframe").contentWindow.postMessage(msg, "*");
      });
    },

    initRightTableFn() {},
  },
};
